<?php

/**
 * 模版生成操作
 * @author M2
 * @version 1.0
 * create Date 2013-07-22
 */
class CreateAction extends PublicAction { 

    public function __construct() {
        parent::__construct();
        set_time_limit(0);
        C(require APPS_PATH.'/cms/Conf/config.php');
        if (!ob_get_level())
            ob_start();
    }

    /**
     * 生产首页
     * M2
     */
    public function create_home() {
        $string = "<select id='pid' name='sid[]' size=30 multiple='multiple' style='width: 300px;'>";
        //得到内容列表的权限
        $rid = M('role_user')->where("user_id =" . $_SESSION['mid'])->field("role_id")->select();
        if ($rid) {
        	$ids = "";
        	foreach ($rid as $v){
        		$ids.= $v['role_id'].',';
        	}
        	$ids=substr($ids,0, strlen($ids)-1);
            $sids = M('access')->join(" as a left join " . C('DB_PREFIX') . "node as n on a.node_id = n.id")
                            ->where(" a.role_id in(" . $ids . ") and a.level=3 and n.name='create_home'")->field("n.sid")->select();
        }
        if (empty($sids)) {
            $sitelist = M('cms_site')->order('siteid asc')->select();
        } else {
            foreach ($sids as $k => $v) {
                $sids[$k] = $v['sid'];
            }
            $map['siteid'] = array('in', implode(",", $sids));
            $sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
        }
        if (!empty($sitelist)) {
            foreach ($sitelist as $k => $v) {
                $string .= "<option value='" . $v['siteid'] . "'>" . $v['name'] . "</option>;";
            }
        }
        $string .= "</select>";
        $this->assign('alist', $string);
        $this->display();
    }

    /**
     * 栏目页
     * M2
     */
    public function create_cate() {
        $this->getCate("1");
        $this->display();
    }

    /**
     * 内容页
     * M2
     */
    public function create_content() {
        $this->getCate("2");
        $this->display();
    }

    /**
     * 得到栏目列表
     * next
     */
    private function getCate($iscontentnode) {
        $siteid = "";
        $sitename = "";
        if ($iscontentnode === "1") {
            $actionstr = "create_cate";
        } else {
            $actionstr = "create_content";
        }

        //得到内容列表的权限
        $rid = M('role_user')->where("user_id =" . $_SESSION['mid'])->field("role_id")->select();
        if ($rid) {
        	$ids = "";
        	foreach ($rid as $v){
        		$ids.= $v['role_id'].',';
        	}
        	$ids=substr($ids,0, strlen($ids)-1);
            $sids = M('access')->join(" as a left join " . C('DB_PREFIX') . "node as n on a.node_id = n.id")
                            ->where(" a.role_id in (" . $ids . ") and a.level=3 and n.name='{$actionstr}'")->field("n.sid")->select();
        }
        if (empty($sids)) {
            $sitelist = M('cms_site')->order('siteid asc')->select();
        } else {
            foreach ($sids as $k => $v) {
                $sids[$k] = $v['sid'];
            }
            $map['siteid'] = array('in', implode(",", $sids));
            $sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
        }
        if (!empty($sitelist)) {
            foreach ($sitelist as $k => $v) {
                $siteid = $siteid . ',' . $v['siteid'];
                $sitename = $sitename . ',' . $v['name'];
            }
        }
        //去掉最前面的,
        if (!empty($siteid)) {
            $siteid = substr($siteid, 1);
            $sitename = substr($sitename, 1);
        }
        $list = D('Category')->channelAllList($siteid, $sitename);
        $string = "<select id='pid' name='pid[]' size=30 multiple='multiple' style='width: 300px;'>";
        if ($iscontentnode == "1") {
            $str = "<option value='\$id,\$siteid' \$selected>\$spacer \$cname</option>;";
        } else {
            $str = "<option value='\$id,\$siteid' \$selected>\$spacer \$cname (\$content_num)</option>;";
        }
        import('Tree');
        $tree = new Tree();
        $tree->init($list);
        $string .= $tree->get_tree_category(0, $str);
        $string .= "</select>";
        $this->assign('alist', $string);
    }

    /**
     * 生产首页
     * M2
     */
    public function create_homepage() {
        G('siteBegin');
        if (empty($_POST['sid']))
            $this->error('请选择要生成的站点首页');

        //得到站点模板
        $data['siteid'] = array('in', $_POST['sid']);
        $data['template_type'] = 'home';
        $templateList = M('cms_templates')->where($data)->select();

        //得到生成页面数
        $countNum = count($templateList);
        $count = 100;
        $b = $count / $countNum;
        $j = 0;

        $this->assign('message', '生成首页');

        $this->load();

        $this->create_ProgressBar(0, 0, $countNum, '首页');
        $n = 1;
        //循环站点模板
        foreach ($templateList as $k => $v) {
        	//OOO  add by jepin id去除重复
        	 clearIds();
        	//OOO  end 
        	
            //得到站点id
            $sid = $v['siteid'];

            //得到全局配置
            $changeStyle = model('Data')->get('cmsconfig:site-' . $sid);

            //得到站点信息
            if (($sited = S('cache_siteid_' . $sid)) === false) {
                $sited = M('cms_site')->where('siteid=' . $sid)->find();
                S('cache_siteid_' . $sid, $sited);
            }

            //得到站点模板目录
            $templatedir = empty($sited['dirname']) ? '' : $sited['dirname'] . '/';
            $templatedir = './' . $templatedir . 'templates/';
            //得到首页栏目数据
            $arr = M('cms_category')
                    ->field('(case when url <> "" then url when createurl <> "" then createurl
                    else (concat("' . $sited['domain'] . '","/",replace((case when artnaming <> ""
                		 then catenaming else ("' . $changeStyle['catenaming'] . '") end),"{cateid}",id))) end) as url,
                    replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,id,cname,content,keywords,description')
                    ->where('siteid = ' . $sid . ' and id=' . $sid)
                    ->find();

            $v['template_name'] = iconv("UTF-8", "GB2312", $v['template_name']);
            if (file_exists($templatedir . $v['template_name'])) {
                $j += $b;
                $content = taglib('YlInclude')->parse($templatedir . $v['template_name'], '', $templatedir);
                $content = taglib('YlInclude')->parse('', $content, $templatedir);
                $content = taglib('YlInclude')->parse('', $content, $templatedir);
                if (strpos($content, '{') && strpos($content, '}')) {
                    preg_match_all('/\{site.(.*?)\}/eis', $content, $out);
                    for ($i = 0; $i < count($out[1]); $i++) {
                        $content = str_ireplace($out[0][$i], $sited[$out[1][$i]], $content);
                    }
                    preg_match_all('/\{Channel.(.*?)\}/eis', $content, $match);
                    for ($i = 0; $i < count($match[1]); $i++) {
                        $content = str_ireplace($match[0][$i], $arr[$match[1][$i]], $content);
                    }
                }
                $content = taglib('YlSite')->parse($content, $sid);
                $content = taglib('YlSearchInput')->parse($content, $sid);
                $content = taglib('YlSqlContents')->parse($content);
                $content = taglib('YlChannels')->parse($content, $sid, $sid, $sited['domain'], $changeStyle);
                $content = taglib('YlContents')->parse($content, $sid, $arr, $sited['domain'], $changeStyle);
                $content = taglib('YlBlock')->parse($content);
                $content = taglib('YlPageChannels')->parse($content, $sid, $sited['domain'], $changeStyle);
                if (!empty($content)) {
                    $content = taglib('YlA')->parse($content, $sid, null, '', $sited['domain'], $changeStyle);
                    $content = taglib('YlChannel')->parse($content, $arr, $sid, $sited['domain'], $changeStyle);
                    $content = taglib('YlImage')->parse($content, null, $sid);
                    $content = taglib('YlAd')->parse($content, $sited);
                    $content = taglib('YlIf')->parse($content, $sited);
                    $content = taglib('YlCount')->parse($content);
                    file_put_contents(SITE_PATH . '/' . $sited['dirname'] . '/' . $v['create_name'], $content);
                }
                $this->create_ProgressBar(round($j), $n++, $countNum, '首页');
            } else {
                echo '<br/>' . $arr['cname'] . '的首页模版不存在' . '<br/>';
            }
        }
        G('siteEnd');
        // dump(G('siteBegin','siteEnd').'s');
        //OOO  add by jepin id去除重复
        clearIds();
        //OOO  end
    }

    /**
     * 生成栏目页面
     * M2
     */
    public function create_catepage() {
        session_write_close();
        G('channelBegin');
        if (empty($_POST['pid']))
            $this->error('请选择要生成的栏目');
        $channelId = $_POST['pid'];

        //一共生成的页面数
        $countNum = count($channelId);
        $count = 100;
        $b = $count / $countNum;
        $j = 0;

        //开始生成
        $this->assign('message', '批量生成栏目页');

        $this->load();
        $this->create_ProgressBar(0, 0, $countNum, '栏目');

        //循环生成所选择的页面
        foreach ($channelId as $k => $channelid) {
            //分拆栏目id与站点id
            $channelidarr = explode(",", $channelid);
            $channelid = $channelidarr[0];
            $sid = $channelidarr[1];

            //得到全局配置
            $changeStyle = model('Data')->get('cmsconfig:site-' . $sid);

            //得到站点信息
            if (($sited = S('cache_siteid_' . $sid)) === false) {
                $sited = M('cms_site')->where('siteid=' . $sid)->find();
                S('cache_siteid_' . $sid, $sited);
            }
            //得到站点目录与模板目录
            $createdir = empty($sited['dirname']) ? '' : $sited['dirname'] . '/';
            $createdir = './' . $createdir;
            $templatedir = $createdir . 'templates/';
            //查询栏目详细资料
            if (($channels = S('cache_channel_' . $channelid)) === false) {
                $channels = M('cms_category')
                        ->field('(case when url <> "" then url when createurl <> "" then createurl
                else (concat("' . $sited['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,id,cname,content,keywords,
                description,catetemplate,arttemplate,createurl,catenaming,artnaming,pagetitle,pagedescription,
                inputtime,updatetime,content_num,pid')
                        ->where('siteid=' . $sid . ' and id=' . $channelid)
                        ->find();
                S('cache_channel_' . $channelid, $channels);
            }
            if (!empty($channels)) {
                if ($channels['catetemplate'] && $channelid != $sid) {
                    $channels['catetemplate'] = iconv("UTF-8", "GB2312", $channels['catetemplate']);
                } else {
                    $channels['catetemplate'] = iconv("UTF-8", "GB2312", $changeStyle['channelTemplate']);
                }
                $j += $b;
                if ($channels['pid'] == 0 || !empty($channels['url'])) {
                    $this->create_ProgressBar(round($j), $k + 1, $countNum, '栏目');
                } else {
                    //处理生成页面路径
                    $channels['createurl'] = trim($channels['createurl']);
                    if (!empty($channels['createurl'])) {
                        $create_name = $channels['createurl'];
                    } else {
                        if ($channels['catenaming'] && $channelid != $sid) {
                            $channels['catenaming'] = common('Array')->getParseTemplate($channels, $channels['catenaming'], 'cateid');
                        } else {
                            $channels['catenaming'] = common('Array')->getParseTemplate($channels, $changeStyle['catenaming'], 'cateid');
                        }
                        $create_name = str_replace('{@ChannelID}', $channels['id'], $channels['catenaming']);
                        $create_name = str_replace('{@Year}', date("Y"), $create_name);
                    }
                    $templateNewPath = $templatedir . $channels['catetemplate'];
                    //读取模板及读取包含文件的内容，一并存到缓存
                    if (($content = S('cache_template_' . $sid . '_' . $templateNewPath)) === false) {
                        $content = taglib('YlInclude')->parse($templateNewPath, '', $templatedir);
                        $content = taglib('YlInclude')->parse('', $content, $templatedir);
                        $content = taglib('YlInclude')->parse('', $content, $templatedir);
                        S('cache_template_' . $sid . '_' . $templateNewPath, $content, 600);
                    }
                    $content = taglib('YlSite')->parse($content, $sid);
                    $content = taglib('YlSearchInput')->parse($content, $sid);
                    $content = taglib('YlLocation')->parse($content, $sid, $channels['id']);
                    $content = taglib('YlNavigation')->parse($content, $sid, $channels['id'], '', $sited['domain'], $changeStyle);
                    $content = taglib('YlChannels')->parse($content, $sid, $channels['id'], $sited['domain'], $changeStyle);
                    if (strpos($content, '{') && strpos($content, '}')) {
                        preg_match_all('/\{site\.(.*?)\}/eis', $content, $out);
                        for ($i = 0; $i < count($out[1]); $i++) {
                            $content = str_ireplace($out[0][$i], $sited[$out[1][$i]], $content);
                        }
                        preg_match_all('/\{Channel\.(.*?)\}/eis', $content, $match);
                        for ($i = 0; $i < count($match[1]); $i++) {
                            $content = str_ireplace($match[0][$i], $channels[$match[1][$i]], $content);
                        }
                    }
                    //广告标签
                    $content = taglib('YlAd')->parse($content, $sited);
                    $content = taglib('YlContents')->parse($content, $sid, $channels, $sited['domain'], $changeStyle);
                    $content = taglib('YlSqlContents')->parse($content);
                    $content = taglib('YlBlock')->parse($content);
                    //OOO jepin  add sqlContent  
                    $content = taglib('YlSqlContent')->parse($content);
                    $content = taglib('YlPageContents')->parse($content, $channels['id'], $sid, $channels, $createdir, $sited['domain'], $changeStyle, $create_name);
                    if (!empty($content)) {
                        $content = taglib('YlPageSqlContents')->parse($content, $channels['id'], $sid, $channels, $createdir, $sited['domain'], $channels, $create_name);
                        if (!empty($content)) {
                            $content = taglib('YlA')->parse($content, $sid, $channels, '4', $sited['domain'], $changeStyle);
                            $content = taglib('YlImage')->parse($content, $channels, $sid);
                            $content = taglib('YlCount')->parse($content, $channels);
                            $content = taglib('YlIf')->parse($content, $channels);
                            $content = taglib('YlChannel')->parse($content, $channels, $sid, $sited['domain'], $changeStyle);
                            if (dirname($createdir . $create_name))
                                mk_dir(dirname($createdir . $create_name));
                            file_put_contents($createdir . $create_name, $content);
                        }
                    }
                    $this->create_ProgressBar(round($j), $k + 1, $countNum, '栏目');
                }
            }
        }
        G('channelEnd');
        // dump(G('channelBegin','channelEnd').'s');
    }

    /**
     * 生成内容页面
     * M2
     */
    public function create_contentpage() {
        session_write_close();
        G('contentBegin');
        if (empty($_POST['pid']))
            $this->error('请选择要生成的栏目');
        $channelId = $_POST['pid'];

        //得到生成页面数
        $channelIdNew = "";
        foreach ($channelId as $kj => $channelid) {
            //分拆栏目id
            $channelidarr = explode(",", $channelid);
            $channelIdNew = $channelIdNew . ',' . $channelidarr[0];
        }
        //去掉最前面的,
        if (!empty($channelIdNew)) {
            $channelIdNew = substr($channelIdNew, 1);
        }
        $data['cid'] = array('in', $channelIdNew);
        $data['status'] = array('neq', '-1');
        $countNum = M('cms_article')->where($data)->count();
        unset($data);
        $count = 100;
        $b = $count / $countNum;
        $j = 0;
        $m = 1;

        $this->assign('message', '批量生成内容页');

        $this->load();
        $this->create_ProgressBar(0, 0, $countNum, '内容');

        foreach ($channelId as $kk => $channelid) {
            //分拆栏目id与站点id
            $channelidarr = explode(",", $channelid);
            $channelid = $channelidarr[0];
            $sid = $channelidarr[1];

            //得到全局配置
            $changeStyle = model('Data')->get('cmsconfig:site-' . $sid);

            //得到站点信息
            if (($sited = S('cache_siteid_' . $sid)) === false) {
                $sited = M('cms_site')->where('siteid=' . $sid)->find();
                S('cache_siteid_' . $sid, $sited);
            }

            //得到站点目录与模板目录
            $createdir = empty($sited['dirname']) ? '' : $sited['dirname'] . '/';
            $createdir = './' . $createdir;
            $templatedir = $createdir . 'templates/';

            //得到要生成的内容数据
            $articleIDList = M('cms_article')->where('status =1 and siteid=' . $sid . ' and cid=' . $channelid)->field('id')->select();
            if (!empty($articleIDList)) {
                //得到要生成的栏目数据
                if (($clist = S('cache_channel_' . $channelid)) === false) {
                    $clist = M('cms_category')
                            ->field('(case when url <> "" then url when createurl <> "" then createurl
                else (concat("' . $sited['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,id,cname,content,keywords,
                description,catetemplate,arttemplate,createurl,catenaming,artnaming,
                inputtime,updatetime,content_num,pid')
                            ->where('siteid=' . $sid . ' and id=' . $channelid)
                            ->find();
                    S('cache_channel_' . $channelid, $clist);
                }
                if ($clist['arttemplate'] && $channelid != $sid) {
                    $clist['arttemplate'] = iconv("UTF-8", "GB2312", $clist['arttemplate']);
                } else {
                    $clist['arttemplate'] = iconv("UTF-8", "GB2312", $changeStyle['contentTemplate']);
                }
                if (!$clist['artnaming'] || $channelid == $sid) {
                    $clist['artnaming'] = $changeStyle['artnaming'];
                }

                //循环生成内容页面
                foreach ($articleIDList as $k => $articleID) {
                	//OOO  add by jepin id去除重复
                	clearIds();
                	//OOO  end
                    if (($contents = S('cache_contents_' . $articleID['id'])) === false) {
                        $contents = M('cms_article')
                                        ->field('(case when url <> "" then url else
                                     (concat("' . $sited['domain'] . '","/",replace(replace("' . $clist['artnaming'] . '","{cateid}",
                                     cid),"{contentid}",id))) end) as url,replace(imageurl,"@","' . $sited['domain'] . '")
                                     as imageurl,replace(big_imageurl,"@","' . $sited['domain'] . '") as big_imageurl,title,subtitle,author,updatetime,inputtime,tags,
                                     url as articleUrl,source,content,summary,group_name_collection,readpoint,keywords,description,create_uid,create_uname,update_uid,
                                    update_uname,fileurl,cid,id,siteid')
                                        ->where('id=' . $articleID['id'])->find();
                        S('cache_contents_' . $articleID['id'], $contents);
                    }
                    if (!empty($contents)) {
                        $j += $b;
                        if (!empty($contents['articleUrl'])) {
                            $this->create_ProgressBar(round($j), $m++, $countNum, '内容');
                        } else {
                            //得到生成页面路径
                            $artnaming = str_replace('{@ChannelID}', $clist['id'], $clist['artnaming']);
                            $artnaming = str_replace('{@ContentID}', $contents['id'], $artnaming);
                            $artnaming = str_replace('{@Year}', date("Y"), $artnaming);
                            $artnaming = str_replace('{cateid}', $contents['cid'], $artnaming);
                            $artnaming = str_replace('{contentid}', $contents['id'], $artnaming);

                            $templateNewPath = $templatedir . $clist['arttemplate'];
                            //把读取模板及读取包含文件的内容，一并存到缓存
                            if (($content = S('cache_template_' . $sid . '_' . $templateNewPath)) === false) {
                                $content = taglib('YlInclude')->parse($templateNewPath, '', $templatedir);
                                $content = taglib('YlInclude')->parse('', $content, $templatedir);
                                $content = taglib('YlInclude')->parse('', $content, $templatedir);
                                S('cache_template_' . $sid . '_' . $templateNewPath, $content, 600);
                            }
                            
                            $content = taglib('YlSite')->parse($content, $sid);
                            $content = taglib('YlSearchInput')->parse($content, $sid);
                            $content = taglib('YlLocation')->parse($content, $sid, '', $contents['cid'], $contents['id']);
                            $content = taglib('YlNavigation')->parse($content, $sid, $contents['cid'], $contents['id'], $sited['domain'], $changeStyle);
                            $content = taglib('YlChannels')->parse($content, $sid, $clist['id'], $sited['domain'], $changeStyle);
                            $content = taglib('YlContents')->parse($content, $sid, $clist, $sited['domain'], $changeStyle);
                            if (strpos($content, '{') && strpos($content, '}')) {
                                preg_match_all('/\{site\.(.*?)\}/eis', $content, $out);
                                for ($i = 0; $i < count($out[1]); $i++) {
                                    $content = str_ireplace($out[0][$i], $sited[$out[1][$i]], $content);
                                }
                                preg_match_all('/\{Channel\.(.*?)\}/eis', $content, $match);
                                for ($i = 0; $i < count($match[1]); $i++) {
                                    $content = str_ireplace($match[0][$i], $clist[$match[1][$i]], $content);
                                }
                                preg_match_all('/\{Content\.(.*?)\}/eis', $content, $match);
                                for ($i = 0; $i < count($match[1]); $i++) {
                                    $content = str_ireplace($match[0][$i], $contents[$match[1][$i]], $content);
                                }
                            }
                            $content = taglib('YlSqlContents')->parse($content);
                            $content = taglib('YlSqlContent')->parse($content);
                            $content = taglib('YlBlock')->parse($content);
                            $content = taglib('YlComments')->parse($content, $contents['id']);
                            $content = taglib('YlA')->parse($content, $sid, $contents, '1', $sited['domain'], $changeStyle);
                            $content = taglib('YlImage')->parse($content, $contents, $sid);
                            $content = taglib('YlContent')->parse($content, $contents, $sited['domain']);
                            $content = taglib('YlChannel')->parse($content, $clist, $sid, $sited['domain'], $changeStyle);
                            //广告标签
                            $content = taglib('YlAd')->parse($content, $sited);
                            $content = taglib('YlCount')->parse($content, $contents);
                            $content = taglib('YlIf')->parse($content, $contents);
                            if (dirname($createdir . $artnaming))
                                mk_dir(dirname($createdir . $artnaming));
                            file_put_contents($createdir . $artnaming, $content);
                            $this->create_ProgressBar(round($j), $m++, $countNum, '内容');
                        }
                    } else {
                        echo '没有可生成的内容';
                    }
                }
            }
        }
        G('contentEnd');
        // dump(G('contentBegin','contentEnd').'s');
    }

    /**
     * 做输出加载进度条动作
     * M2
     */
    public function create_ProgressBar($total, $message, $count, $t) {
        echo '<script type="text/javascript">control(' . $total . ',' . $message . ',' . $count . ',\'' . $t . '\');</script>';
        ob_flush();
        flush();
    }

    /**
     * 开始输出加载进度条页面
     * M2
     */
    public function load() {
        $this->display('create');
    }

    /*     * **************************** create by tony ******************************** */

    /**
     * 呈现生成栏目页的进度条
     */
    public function channelFootbar() {
        if (empty($_POST['pid'])) {
            $this->error('请选择要生成的栏目');
        }
        $channelId = $_POST['pid'];

        //一共生成的页面数
        $countNum = count($channelId);

        //生成一个随机token，避免多人同时操作时发生错误
        $token = md5(rand_string(6));
        //缓存需要生成的栏目页
        S('cache_channel_creating'.$token, $channelId,null,'File',C('CREATE_CACHE_OPTION'));
        //session('cache_channel_creating'.$token, json_encode($channelId));

        $this->assign('token',$token);
        $this->assign('total', $countNum);
        $this->assign('message', '批量生成栏目页');
        $this->display('create_channelbar');
    }

    /**
     * 批量生成栏目页，一个栏目页分为好几页，采用异步ajax一次生成一个（包含分页的栏目页）栏目页
     */
    public function createCatePage() {
        session_write_close();
        $token = $_GET['token'];
        $time = intval($_GET['i']);
        if(empty($time)){
            $this->ajaxReturn(null, '参数错误', 0);
        }
        //读取缓存
        if (!($pages = S('cache_channel_creating'.$token,'',null,'File',C('CREATE_CACHE_OPTION')))) {
            //缓存过期，刷新页面
            $this->ajaxReturn(null, '缓存过期，刷新页面即可', 0);
        };
        //总栏目数
        $channelid = array();
        $count = count($pages);
        if($time <= $count){
            $channelid = $pages[$time-1];
        }
        unset($pages);
        if(!empty($channelid)){
            //分拆栏目id与站点id
            $channelidarr = explode(",", $channelid);
            $channelid = $channelidarr[0];
            $sid = $channelidarr[1];

            //得到全局配置
            $changeStyle = model('Data')->get('cmsconfig:site-' . $sid);

            //得到站点信息
            if (($sited = S('cache_siteid_' . $sid)) === false) {
                $sited = M('cms_site')->where('siteid=' . $sid)->find();
                S('cache_siteid_' . $sid, $sited);
            }
            //得到站点目录与模板目录
            $createdir = empty($sited['dirname']) ? '' : $sited['dirname'] . '/';
            $createdir = './' . $createdir;
            $templatedir = $createdir . 'templates/';
            //查询栏目详细资料
            if (($channels = S('cache_channel_' . $channelid)) === false) {
                $channels = M('cms_category')
                        ->field('(case when url <> "" then url when createurl <> "" then createurl
                    else (concat("' . $sited['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                    replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,id,plistid,cname,content,keywords,
                    description,catetemplate,arttemplate,createurl,catenaming,artnaming,pagetitle,pagedescription,
                    inputtime,updatetime,content_num,pid')
                        ->where('siteid=' . $sid . ' and id=' . $channelid)
                        ->find();
                S('cache_channel_' . $channelid, $channels);
            }
            if (!empty($channels)) {
                if ($channels['catetemplate'] && $channelid != $sid) {
                    $channels['catetemplate'] = iconv("UTF-8", "GB2312", $channels['catetemplate']);
                } else {
                    $channels['catetemplate'] = iconv("UTF-8", "GB2312", $changeStyle['channelTemplate']);
                }
                if ($channels['pid'] != 0 && empty($channels['url'])) {
                    //处理生成页面路径
                    $channels['createurl'] = trim($channels['createurl']);
                    if (!empty($channels['createurl'])) {
                        $create_name = $channels['createurl'];
                        $channels['catenaming'] = $channels['createurl'];
                    } else {
                        if ($channels['catenaming'] && $channelid != $sid) {
                            $channels['catenaming'] = common('Array')->getParseTemplate($channels, $channels['catenaming'], 'cateid');
                        } else {
                            $channels['catenaming'] = common('Array')->getParseTemplate($channels, $changeStyle['catenaming'], 'cateid');
                        }
                        $create_name = str_replace('{@ChannelID}', $channels['id'], $channels['catenaming']);
                        $create_name = str_replace('{@Year}', date("Y"), $create_name);
                        $channels['catenaming'] = $create_name;
                    }
                    $templateNewPath = $templatedir . $channels['catetemplate'];
                    //读取模板及读取包含文件的内容，一并存到缓存
                    if (($content = S('cache_template_' . $sid . '_' . $templateNewPath)) === false) {
                        $content = taglib('YlInclude')->parse($templateNewPath, '', $templatedir);
                        $content = taglib('YlInclude')->parse('', $content, $templatedir);
                        $content = taglib('YlInclude')->parse('', $content, $templatedir);
                        S('cache_template_' . $sid . '_' . $templateNewPath, $content, 600);
                    }
                    $content = taglib('YlSite')->parse($content, $sid);
                    $content = taglib('YlSearchInput')->parse($content, $sid);
                    $content = taglib('YlLocation')->parse($content, $channels, $sited, $changeStyle);
                    $content = taglib('YlNavigation')->parse($content, $sid, $channels['id'], '', $sited['domain'], $changeStyle);
                    $content = taglib('YlChannels')->parse($content, $sid, $channels['id'], $sited['domain'], $changeStyle);
                    if (strpos($content, '{') && strpos($content, '}')) {
                        preg_match_all('/\{site\.(.*?)\}/eis', $content, $out);
                        for ($i = 0; $i < count($out[1]); $i++) {
                            $content = str_ireplace($out[0][$i], $sited[$out[1][$i]], $content);
                        }
                        preg_match_all('/\{Channel\.(.*?)\}/eis', $content, $match);
                        for ($i = 0; $i < count($match[1]); $i++) {
                            $content = str_ireplace($match[0][$i], $channels[$match[1][$i]], $content);
                        }
                    }
                    //广告标签
                    $content = taglib('YlAd')->parse($content, $sited);
                    $content = taglib('YlContents')->parse($content, $sid, $channels, $sited['domain'], $changeStyle);
                    $content = taglib('YlSqlContents')->parse($content);
                    $content = taglib('YlBlock')->parse($content);
                    //OOO jepin  add sqlContent  
                    $content = taglib('YlSqlContent')->parse($content);
                    $content = taglib('YlPageContents')->parse($content, $channels['id'], $sid, $channels, $createdir, $sited['domain'], $changeStyle, $create_name,$token);
                    $content = taglib('YlIf')->parse($content, $channels);
                    if ($content != 'complete' && $content != 'uncomplete') {
                        $content = taglib('YlPageSqlContents')->parse($content, $channels['id'], $sid, $channels, $createdir, $sited['domain'], $channels, $create_name);
                        if (!empty($content)) {
                            $content = taglib('YlA')->parse($content, $sid, $channels, '4', $sited['domain'], $changeStyle);
                            $content = taglib('YlImage')->parse($content, $channels, $sid);
                            $content = taglib('YlCount')->parse($content, $channels);
                            $content = taglib('YlIf')->parse($content, $channels);
                            $content = taglib('YlChannel')->parse($content, $channels, $sid, $sited['domain'], $changeStyle);
                            if (dirname($createdir . $create_name))
                                mk_dir(dirname($createdir . $create_name));
                            file_put_contents($createdir . $create_name, $content);
                        }
                    }
                }
                //OOO  add by jepin id去除重复
                clearIds();
                //OOO  end
                if('uncomplete' == $content){
                    $data = array(
                        'footbar'=>'uncomplete',
                        'completePage'=>$time-1
                    );
                }else{
                    $data = array(
                        'completePage'=>$time,
                    );
                }
                
                if(($time == $count) && !S('cache_channel_create_count'.$channels['id'].$token,'',null,'File',C('CREATE_CACHE_OPTION'))){
                    S('cache_channel_creating'.$token,null,null,'File',C('CREATE_CACHE_OPTION'));
                }
                $this->ajaxReturn($data,'栏目生成中',1);
            } else {
                $this->ajaxReturn(null, '获取栏目信息失败', 0);
            }
        }else{
            S('cache_channel_creating'.$token,null,null,'File',C('CREATE_CACHE_OPTION'));
            $data = array(
                'completePage'=>$count,
            );
            $this->ajaxReturn($data,'栏目生成中',1);
        }
    }

    /**
     * 每次请求生成的页面数量
     */
    private $_eachPage = 50;

    /**
     * 呈现生成内容页的进度条
     */
    public function footBar() {
        if (empty($_POST['pid']))
            $this->error('请选择要生成的栏目');
        $channelId = $_POST['pid'];

        //得到生成页面数
        $channelIdNew = "";
        //用以缓存需要生成的页面的信息
        $pages = array();
        foreach ($channelId as $kj => $channelid) {
            //分拆栏目id
            $channelidarr = explode(",", $channelid);
            $channelIdNew = $channelIdNew . ',' . $channelidarr[0];
            $sid = $channelidarr[1];
            //得到站点信息
            if (($sited = S('cache_siteid_' . $sid)) === false) {
                $sited = M('cms_site')->where('siteid=' . $sid)->find();
                S('cache_siteid_' . $sid, $sited);
            }
            
            $where = array(
                'status'=>1,
                'siteid'=>$sid,
                'cid'=>$channelidarr[0]
            );
            
            if($_POST['type'] == 'timezone'){
                if(empty($_POST['from'])){
                    $this->error("开始时间不能为空");
                }
                $from = strtotime($_POST['from']);
                if(!empty($_POST['to'])){
                    $to = strtotime($_POST['to']);
                }else{
                    $to = time();
                }
                $where['c.commenttime'] = array('between',array(
                    $from,$to
                ));
                $join = array($this->_dbPrefix.'cms_comments c on '.$this->_dbPrefix.'cms_article.id = c.article_id');
                $articleIds = M('cms_article')->join($join)->where($where)->field($this->_dbPrefix.'cms_article.id')->select();
            }else{
                //查出每个栏目下面的所有contentid
                $articleIds = M('cms_article')->where($where)->field('id')->select();
            }
            //缓存每个页面的id，所属的栏目id，所属的站点id（一起缓存）
            foreach ($articleIds as $id) {
                $pages[] = array(
                    'id' => $id['id'], //contentid
                    'cid' => $channelidarr[0], //channelid
                    'sid' => $channelidarr[1], //siteid
                );
            }
        }

        if(count($pages) == 0){
            $this->error("您选择的条件下的内容页数量为0，请重新选择条件~");
        }
        //生成一个随机token，避免多人同时操作时发生错误
        $token = md5(rand_string(6));
        //缓存需要生成的页面,防止生成页面过程中发生清除缓存操作
        S('cache_content_creating'.$token,$pages,null,'File',C('CREATE_CACHE_OPTION'));
        //session的过期时间是个坑，改用S函数
//        session('cache_content_creating'.$token, json_encode($pages));
        $this->assign('token', $token);
        $this->assign('total', count($pages));
        $this->assign('message', '批量生成内容页');
        $this->display('create_contentbar');
    }

    /**
     * 生成内容页
     */
    public function createContentPage() {
        //内容生成页面耗时比较久，会阻塞同一个session下的其它请求，关闭session写操作，
        //可以避免阻塞其它页面，但之后的session写操作也将失效，但读session正常
        session_write_close();
        $token = $_GET['token'];
        //第$time次请求
        $time = intval($_GET['i']);
        if(empty($time)){
            $this->ajaxReturn(null, '参数错误', 0);
            return;
        }
        //读取缓存
        if (!($pages = S('cache_content_creating'.$token,'',null,'File',C('CREATE_CACHE_OPTION')))) {
            //缓存过期，刷新页面
            $this->ajaxReturn(null, '缓存过期，刷新页面即可', 0);
        };
        $count = count($pages);//页面总数
        //计算每次生成的页面个数,小于500个页面就按总页面的十分之一来，大于就默认每50个页面一次
        if($count < 500){
            $this->_eachPage = ceil($count/10);
        }
        $dealPages = array();
        if(($time-1)*$this->_eachPage <= $count){
            $dealPages = array_slice($pages, $this->_eachPage*($time-1), $this->_eachPage);
        }
        unset($pages);
        $flag = '';
        foreach ($dealPages as $page) {
        	//OOO  add by jepin id去除重复
        	clearIds();
        	//OOO  end
            if ($flag != $page['sid'] . '_' . $page['cid']) {
                //变量存储前一次的sid和cid，用来判断当前的sid和cid是否和前一次一样，如果一样，则下面的也一样
                $flag = $page['sid'] . _ . $page['cid'];
                //得到全局配置
                $changeStyle = model('Data')->get('cmsconfig:site-' . $page['sid']);

                //得到站点信息
                if (($sited = S('cache_siteid_' . $page['sid'])) === false) {
                    $sited = M('cms_site')->where('siteid=' . $page['sid'])->find();
                    S('cache_siteid_' . $page['sid'], $sited);
                }

                //得到站点目录与模板目录
                $createdir = empty($sited['dirname']) ? '' : $sited['dirname'] . '/';
                $createdir = './' . $createdir;
                $templatedir = $createdir . 'templates/';

                //得到要生成的栏目数据
                if (($clist = S('cache_channel_' . $page['cid'])) === false) {
                    $clist = M('cms_category')
                            ->field('(case when url <> "" then url when createurl <> "" then createurl
                else (concat("' . $sited['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                replace(imageurl,"@","' . $sited['domain'] . '") as imageurl,id,plistid,cname,content,keywords,
                description,catetemplate,arttemplate,createurl,catenaming,artnaming,
                inputtime,updatetime,content_num,pid')
                            ->where('siteid=' . $page['sid'] . ' and id=' . $page['cid'])
                            ->find();
                    S('cache_channel_' . $page['cid'], $clist);
                }
                if ($clist['arttemplate'] && $page['cid'] != $page['sid']) {
                    $clist['arttemplate'] = iconv("UTF-8", "GB2312", $clist['arttemplate']);
                } else {
                    $clist['arttemplate'] = iconv("UTF-8", "GB2312", $changeStyle['contentTemplate']);
                }
                if (!$clist['artnaming'] || $page['cid'] == $page['sid']) {
                    $clist['artnaming'] = $changeStyle['artnaming'];
                }
            }

            if (($contents = S('cache_contents_' . $page['id'])) === false) {
                $contents = M('cms_article')
                                ->field('(case when url <> "" then url else
                                     (concat("' . $sited['domain'] . '","/",replace(replace("' . $clist['artnaming'] . '","{cateid}",
                                     cid),"{contentid}",id))) end) as url,replace(imageurl,"@","' . $sited['domain'] . '")
                                     as imageurl,replace(big_imageurl,"@","' . $sited['domain'] . '") as big_imageurl,title,subtitle,author,updatetime,inputtime,tags,
                                     url as articleUrl,source,content,summary,group_name_collection,readpoint,keywords,description,create_uid,create_uname,update_uid,
                                    update_uname,fileurl,cid,id,siteid,comment_count')
                                ->where('id=' . $page['id'])->find();
                S('cache_contents_' . $page['id'], $contents);
            }
            if (!empty($contents['articleUrl'])) {
                continue;
            } else {
                //得到生成页面路径
                $artnaming = str_replace('{@ChannelID}', $clist['id'], $clist['artnaming']);
                $artnaming = str_replace('{@ContentID}', $contents['id'], $artnaming);
                $artnaming = str_replace('{@Year}', date("Y"), $artnaming);
                $artnaming = str_replace('{cateid}', $contents['cid'], $artnaming);
                $artnaming = str_replace('{contentid}', $contents['id'], $artnaming);

                $templateNewPath = $templatedir . $clist['arttemplate'];
                //把读取模板及读取包含文件的内容，一并存到缓存
                if (($content = S('cache_template_' . $page['sid'] . '_' . $templateNewPath)) === false) {
                    $content = taglib('YlInclude')->parse($templateNewPath, '', $templatedir);
                    $content = taglib('YlInclude')->parse('', $content, $templatedir);
                    $content = taglib('YlInclude')->parse('', $content, $templatedir);
                    S('cache_template_' . $page['sid'] . '_' . $templateNewPath, $content, 600);
                }
                
                $content = taglib('YlSite')->parse($content, $page['sid']);
                $content = taglib('YlSearchInput')->parse($content, $page['sid']);
                $content = taglib('YlLocation')->parse($content, $sited, $clist, $changeStyle);
                $content = taglib('YlNavigation')->parse($content, $page['sid'], $contents['cid'], $contents['id'], $sited['domain'], $changeStyle);
                $content = taglib('YlChannels')->parse($content, $page['sid'], $clist['id'], $sited['domain'], $changeStyle);
                $content = taglib('YlContents')->parse($content, $page['sid'], $clist, $sited['domain'], $changeStyle,$contents['id']);
                if (strpos($content, '{') && strpos($content, '}')) {
                    preg_match_all('/\{site\.(.*?)\}/eis', $content, $out);
                    for ($i = 0; $i < count($out[1]); $i++) {
                        $content = str_ireplace($out[0][$i], $sited[$out[1][$i]], $content);
                    }
                    preg_match_all('/\{Channel\.(.*?)\}/eis', $content, $match);
                    for ($i = 0; $i < count($match[1]); $i++) {
                        $content = str_ireplace($match[0][$i], $clist[$match[1][$i]], $content);
                    }
                    preg_match_all('/\{Content\.(.*?)\}/eis', $content, $match);
                    for ($i = 0; $i < count($match[1]); $i++) {
                        $content = str_ireplace($match[0][$i], $contents[$match[1][$i]], $content);
                    }
                }
                $content = taglib('YlSqlContents')->parse($content);
                $content = taglib('YlSqlContent')->parse($content);
                $content = taglib('YlBlock')->parse($content);
                $content = taglib('YlComments')->parse($content, $contents['id']);
                $content = taglib('YlA')->parse($content, $page['sid'], $contents, '1', $sited['domain'], $changeStyle);
                $content = taglib('YlImage')->parse($content, $contents, $page['sid']);
                $content = taglib('YlContent')->parse($content, $contents, $sited['domain']);
                $content = taglib('YlChannel')->parse($content, $clist, $page['sid'], $sited['domain'], $changeStyle);
                //广告标签
                $content = taglib('YlAd')->parse($content, $sited);
                $content = taglib('YlCount')->parse($content, $contents);
                $content = taglib('YlIf')->parse($content, $contents);
                if (dirname($createdir . $artnaming))
                    mk_dir(dirname($createdir . $artnaming));
                file_put_contents($createdir . $artnaming, $content);
            }
        }

        //生成相应的进度条
        if($time*$this->_eachPage > $count){
            $data = array(
                'completePage' => $count,
            );
            S('cache_content_creating'.$token,null,null,'File',C('CREATE_CACHE_OPTION'));
        }else{
            $data = array(
                'completePage' => $time*$this->_eachPage
            );
        }
        $this->ajaxReturn($data, '页面生成中', 1);
    }
}

?>
